import AbsExpression from "../abstract/AbsExpression";
import MetaData from "../MetaData";
import TableExpression from "../TableExpression";
import StringUtils from "../../utils/StringUtils";
import UnchangedExpression from "./UnchangedExpression";

class FieldExpression extends AbsExpression {
    public prefix: string;
    protected field: string;

    constructor(field: string, prefix: string | MetaData = '', metadata?: MetaData, position: number = 0) {
        super();
        if (typeof prefix !== 'string') {
            metadata = prefix;
            prefix = "";
        }
        this.prefix = prefix;
        if (metadata && this.prefix) {
            metadata.add(new UnchangedExpression(prefix, metadata,"prefix"), metadata.expressionList.length - position)
        }
        let alias = (metadata?.table as TableExpression)?.getAlias() || "";
        if (field.includes(".")) {
            if (!field.includes("`")) {
                this.field = "`" + field.replace(/[a-zA-Z0-9_-]*?\./, "$&.`").replace("..", "`.") + "`";
            } else {
                this.field = field;
            }
        } else {
            if (field[0] === '`') {
                this.field = StringUtils.postFill(alias, "." + field, field);
            } else {
                this.field = StringUtils.postFill(alias, ".`" + metadata?.handlSqlField(field) + "`", "`" + field + "`");
            }
        }
    }

    toLocaSql(): string {
        return this.field;
    }
}

export = FieldExpression;